﻿using System;
using System.Data;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Accord.Controls;
using Accord.Math;
using Accord.Statistics.Analysis;
using Accord.Statistics.Formats;
using ZedGraph;
using Components;
using System.Collections.Generic;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private PrincipalComponentAnalysis pca;
        private DescriptiveAnalysis sda;

        string[] columnNames;
        double[,] result;

        public Form1()
        {
            InitializeComponent();
            dgvAnalysisSource.AutoGenerateColumns = true;
            dgvProjectionResult.AutoGenerateColumns = true;
            openFileDialog1.InitialDirectory = Path.Combine(Application.StartupPath, "Resources");
        }

     

       

        private void btnSampleRunAnalysis_Click(object sender, EventArgs e)
        {
            // Save any pending changes 
            dgvAnalysisSource.EndEdit();

            if (dgvAnalysisSource.DataSource == null)
            {
                MessageBox.Show("Please load some data using File > Open!");
                return;
            }


            // Create a matrix from the source data table
            double[,] sourceMatrix = (dgvAnalysisSource.DataSource as DataTable).ToMatrix(out columnNames);

            // Create and compute a new Simple Descriptive Analysis
            sda = new DescriptiveAnalysis(sourceMatrix, columnNames);

            sda.Compute();

            // Show the descriptive analysis on the screen
            //dgvDistributionMeasures.DataSource = sda.Measures;

            // Populates statistics overview tab with analysis data
           // dgvStatisticCenter.DataSource = new ArrayDataView(sda.DeviationScores, columnNames);
           // dgvStatisticStandard.DataSource = new ArrayDataView(sda.StandardScores, columnNames);

          //  dgvStatisticCovariance.DataSource = new ArrayDataView(sda.CovarianceMatrix, columnNames);
          //  dgvStatisticCorrelation.DataSource = new ArrayDataView(sda.CorrelationMatrix, columnNames);


            AnalysisMethod method = (AnalysisMethod)cbMethod.SelectedValue;

            // Create the Principal Component Analysis of the data 
            pca = new PrincipalComponentAnalysis(sda.Source, method);


            pca.Compute();  // Finally, compute the analysis!


            // Populate components overview with analysis data
            //dgvFeatureVectors.DataSource = new ArrayDataView(pca.ComponentMatrix);
           // dgvPrincipalComponents.DataSource = pca.Components;
           // dgvProjectionComponents.DataSource = pca.Components;
           // distributionView.DataSource = pca.Components;
          //  cumulativeView.DataSource = pca.Components;

            //numComponents.Maximum = pca.Components.Count;
          //  numComponents.Value = 1;
          //  numThreshold.Value = (decimal)pca.Components[0].CumulativeProportion * 100;
        }

        protected override void OnLoad(EventArgs e)
        {
            Array methods = Enum.GetValues(typeof(AnalysisMethod));
            this.cbMethod.DataSource = methods;
        }

      

        private void MenuFileOpen_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
            {
                string filename = openFileDialog1.FileName;
                string extension = Path.GetExtension(filename);
                if (extension == ".xls" || extension == ".xlsx")
                {
                    ExcelReader db = new ExcelReader(filename, true, false);
                    TableSelectDialog t = new TableSelectDialog(db.GetWorksheetList());

                    if (t.ShowDialog(this) == DialogResult.OK)
                    {
                        this.dgvAnalysisSource.DataSource = db.GetWorksheet(t.Selection);
                        //this.dgvProjectionSource.DataSource = db.GetWorksheet(t.Selection);
                    }
                }
                else if (extension == ".xml")
                {
                    DataTable dataTableAnalysisSource = new DataTable();
                    dataTableAnalysisSource.ReadXml(openFileDialog1.FileName);

                    this.dgvAnalysisSource.DataSource = dataTableAnalysisSource;
                   // this.dgvProjectionSource.DataSource = dataTableAnalysisSource.Clone();
                }
            }
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new Form2().ShowDialog(this);
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btnShift_Click(object sender, EventArgs e)
        {
            if (pca == null || dgvAnalysisSource.DataSource == null)
            {
                MessageBox.Show("Please compute the analysis first.");
                return;
            }

            // Save any pending changes 
            dgvAnalysisSource.EndEdit();

            string[] colNames;
            int components = 2;
            double[,] projectionSource = (dgvAnalysisSource.DataSource as DataTable).ToMatrix(out colNames);

            // Compute the projection
            double[,] projection = pca.Transform(projectionSource, components);
            result = projection;

            dgvProjectionResult.DataSource = new ArrayDataView(projection, GenerateComponentNames(components));
            
        }
        private string[] GenerateComponentNames(int number)
        {
            string[] names = new string[number];
            for (int i = 0; i < names.Length; i++)
            {
                names[i] = "Component " + (i + 1);
            }
            return names;
        }
        private void exportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (saveFileDialog1.ShowDialog(this) == DialogResult.OK)
            {
                //(dgvProjectionResult.DataSource as DataTable).WriteXml(saveFileDialog1.FileName, XmlWriteMode.WriteSchema);

              //  System.IO.File.WriteAllLines(saveFileDialog1.FileName, result.se );
                List<double> arr = new List<double>();
                using (StreamWriter sr = new StreamWriter(saveFileDialog1.FileName))
                {
                    foreach (var item in result)
                    {
                       arr.Add(item);
                    }
                    for (int i = 0; i < arr.Count; i=i+1) 
                    {
                        sr.WriteLine(arr[i] + " " + arr[++i]);
                    }
                }
            }
        }
    }
}
